import 'package:flutter/material.dart';
import 'package:flutter_base_app/dialog/common/common_select_dialog.dart';
import 'package:flutter_base_framework/base_framework_export.dart';
import 'package:flutter_common_utils/common_utils_export.dart';
import 'package:flutter_live_data/live_data_export.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:flutter_base_app/constant/sp_key.dart';
import 'package:flutter_base_app/export.dart';
import 'package:flutter_base_app/utils/http/http_proxy.dart';
import 'package:flutter_base_app/utils/user/user_help.dart';

import '../../../constant/event_bus_key.dart';
import '../../../router/routes_manager.dart';
import '../../../utils/http/http_manager.dart';
import '../vm/test_vm.dart';

class TestPage extends BasePage {
  const TestPage({super.key});

  @override
  State<TestPage> createState() => _TestPageState();
}

class _TestPageState extends BaseMvvmState<TestPage, TestVm> {
  _TestPageState() : super(TestVm());

  @override
  void initState() {
    super.initState();
    title.value = "Test";
    vm.refreshData(isShowLoading: true);
  }

  @override
  Widget buildWidget(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10),
      child: Wrap(
        spacing: 10,
        children: [
          OutlinedButton(
            onPressed: () {
              _showProxyDialog();
            },
            child: const Text("设置代理"),
          ),
          OutlinedButton(
            onPressed: () {
              _showHostDialog();
            },
            child: const Text("切换环境"),
          ),
        ],
      ),
    );
  }

  void _showHostDialog() {
    final currentType = HttpManager.BASE_URL;
    final data = ["清除", "测试地址", "正式地址"];
    CommonSelectDialog<String>(
      title: "请选择环境",
      data: data,
      selected: currentType == HttpManager.URL_PROD
          ? "正式地址"
          : currentType == HttpManager.URL_TEST
              ? "测试地址"
              : "清除",
      onSelect: (value) {
        final index = data.indexOf(value);
        if (index == 0) {
          SpKey.BASE_URL_TYPE.storeRemove();
        } else {
          SpKey.BASE_URL_TYPE.putStore(index);
        }
        HttpManager.initBaseHost();
        if (currentType != HttpManager.BASE_URL) {
          UserHelp.logout();
        }
      },
    ).show();
  }

  void _onScanProxyClick(int port) async {
    final loadCtrl = showLoadingDialog(msg: "正在扫描...");
    final List<String> proxy = await HttpProxy.getLocalCharlesProxy(port: port);
    loadCtrl.dismiss();
    //显示扫描结果对话框列表
    SmartDialog.show(
      tag: "proxyDialogList",
      clickMaskDismiss: true,
      builder: (context) {
        return AlertDialog(
          title: Text("代理列表"),
          content: SizedBox(
            height: 200,
            child: ListView.builder(
              itemCount: proxy.length,
              padding: EdgeInsets.zero,
              itemBuilder: (context, index) {
                final text = "${proxy[index]}:$port";
                return ListTile(
                  title: Text(text),
                  onTap: () {
                    SmartDialog.dismiss(tag: "proxyDialogList");
                    SmartDialog.dismiss(tag: "proxyDialog");
                    HttpProxy.proxySpKey.putStore(text);
                    EventBusKey.HTTP_PROXY_CHANGE.busPost(text);
                  },
                );
              },
            ),
          ),
        );
      },
    );
  }

  void _showProxyDialog() {
    SmartDialog.show(
        tag: "proxyDialog",
        clickMaskDismiss: true,
        builder: (context) {
          final TextEditingController _controller =
              TextEditingController(text: HttpProxy.proxySpKey.getStore(def: ""));
          final isShowClean = _controller.text.isNotEmpty.obs;
          return AlertDialog(
            contentPadding: const EdgeInsets.symmetric(horizontal: 15),
            title: const Text('请输入代理'),
            content: IntrinsicHeight(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                spacing: 10,
                children: [
                  SizedBox(height: 10),
                  Text("代理地址(如：192.168.1.10:8888)"),
                  Text("扫描功能请输入端口号(默认8888)"),
                  Text("清空输入框保存后清除代理"),
                  TextFormField(
                    controller: _controller,
                    onChanged: (text) {
                      isShowClean.value = _controller.text.isNotEmpty;
                    },
                    decoration: InputDecoration(
                      labelText: "代理地址",
                      suffixIcon: Obx(() => Visibility(
                            visible: isShowClean.value,
                            child: IconButton(
                              onPressed: () {
                                _controller.clear();
                                isShowClean.value = false;
                              },
                              icon: const Icon(
                                Icons.clear,
                                size: 16,
                              ),
                            ),
                          )),
                    ),
                  ),
                  Row(
                    children: [
                      TextButton(
                        onPressed: () {
                          _onScanProxyClick(_controller.text.toIntOrNull() ?? 8888);
                        },
                        child: const Text('扫描'),
                      ),
                      TextButton(
                        child: const Text('本地'),
                        onPressed: () {
                          _controller.text = "127.0.0.1:8888";
                          isShowClean.value = _controller.text.isNotEmpty;
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
            actionsPadding: EdgeInsets.zero,
            actions: <Widget>[
              TextButton(
                child: const Text('取消'),
                onPressed: () {
                  SmartDialog.dismiss(tag: "proxyDialog");
                },
              ),
              TextButton(
                child: const Text('确认'),
                onPressed: () {
                  HttpProxy.proxySpKey.putStore(_controller.text);
                  EventBusKey.HTTP_PROXY_CHANGE.busPost(_controller.text);
                  SmartDialog.dismiss(tag: "proxyDialog");
                },
              ),
            ],
          );
        });
  }

  @override
  void dispose() {
    super.dispose();
  }
}

class TestJumpWidget extends StatelessWidget {
  final Widget child;

  const TestJumpWidget({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    return Builder(builder: (context) {
      var time = 0;
      return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onPanDown: (details) {
          LogUtils.e("onPanDown");
        },
        onDoubleTap: () {
          LogUtils.e("onDoubleTap");
          time = currentTimeMillis;
        },
        onLongPressStart: (details) {
          LogUtils.e("onLongPressStart");
        },
        onLongPressEnd: (details) {
          if (time != 0 && currentTimeMillis - time > 3000) {
            LogUtils.e("onLongPressEnd");
            RouterJump.test();
          }
        },
        child: child,
      );
    });
  }
}
// OutlinedButton(
// onPressed: () {
// LogUtils.e("OutlinedButton pressed");
// },
// child: const Text("OutlinedButton")),
// IconButton(
// onPressed: () {
// LogUtils.e("IconButton pressed");
// },
// icon: const Icon(Icons.sensor_occupied_rounded)),
// ElevatedButton(
// style: ElevatedButton.styleFrom(
// padding: EdgeInsets.zero, // 去除内边距
// backgroundColor: Colors.blue, // 背景色,
// shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
// minimumSize: const Size(double.minPositive, 30),
// ),
// onPressed: () {
// LogUtils.e("ElevatedButton Custom pressed");
// },
// child: const Text("ElevatedButton Custom")),
// const Text("Row"),
// Container(
// constraints: const BoxConstraints(
// maxWidth: 200,
// maxHeight: double.infinity,
// ),
// color: Colors.red,
// padding: const EdgeInsets.all(10),
// child: Text(
// "aaaaaaaaaaabwwwwwwwwwbbbbbbbbbb${vm.counter}",
// softWrap: false,
// overflow: TextOverflow.clip,
// maxLines: 3,
// style: const TextStyle(fontSize: 20),
// ),
// ),
// Container(
// margin: const EdgeInsets.only(top: 10),
// constraints: const BoxConstraints(
// maxWidth: 200,
// maxHeight: 40,
// ),
// child: TextField(
// decoration: const InputDecoration(
// contentPadding: EdgeInsets.all(10),
// hintText: "输入1",
// border: OutlineInputBorder(),
// floatingLabelBehavior: FloatingLabelBehavior.never,
// ),
// keyboardType: TextInputType.number,
// inputFormatters: [
// // FilteringTextInputFormatter.digitsOnly,
// // 只允许输入数字
// FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d*$')),
// // 只允许输入数字和小数点
// ],
// onChanged: (value) {
// LogUtils.e("输入1改变: $value");
// },
// ),
// ),
// Image.asset(
// Assets.imgIcTips,
// width: 100,
// height: 100,
// ),
// SvgPicture.asset(Assets.svgIcSuccess, width: 100, height: 100),
// Text(
// '${vm.counter}',
// style: Theme.of(context).textTheme.headlineMedium,
// ),
